package Util::TopicType::TopicType;
use Moose;
use namespace::autoclean;

has 'schema' => (
	is => 'rw',
	required => 1,
	isa => 'DBIx::Class::Schema',
);

sub get_all_topic_types{
	my ($self) = @_;

	return $self->schema->resultset('TopicType')->search({},{});
}

sub get_topic_count{
	my ($self) = @_;

	return $self->schema->resultset('TopicType')->search()->count;
}

sub get_topic_for_university{
	my ($self, $university_id) = @_;

	my @topics = $self->schema->resultset('Topic')->search(
			{'university.id' => $university_id},
			{
				select => [
					'me.id',
					'me.author_id',
					'me.title',
					'me.body',
					'me.created',
					'me.updated'
				],
				as => [qw/
					id	
					author_id	
					title
					body
					created
					updated
				/],
				join => {'users' => 'university'},
				group_by => [qw/me.id/],
				order_by=>{-desc=>"me.updated"},
				page=>1,
				rows =>10 
			}
		);
	return \@topics;
}
sub topic_search{
	my ($self, $page, $rows) = @_;

	my @topics = $self->schema->resultset('Topic')->search(
			{},
			{
				select => [
					'me.id',
					'me.author_id',
					'me.title',
					'me.body',
					'me.created',
					'me.updated',
					{count => 'comments.id', -as=> 'comments_count'}
				],
				as => [qw/
					id	
					author_id	
					title
					body
					created
					updated
					comments_count		
				/],
				join => {'commented_item' => 'comments'},
				group_by => [qw/me.id/],
				order_by=>{-desc=>"me.updated"},
				page=>$page,
				rows => $rows
			}
		);
	return \@topics;
}

sub find_last_upd_user{
	my ($self) = @_;

	my $rows = 20;
	my @users= $self->schema->resultset('User')->search(
			{},
			{
				select => [
					'me.id',
					'me.username',
					'me.photo',
					{max => 'upd_topic.updated', -as => 'last_upd'}
				],
				as => [qw/
					id
					username
					photo
					last_upd
				/],
				join => ['upd_topic'],
				group_by => 'me.id',
				order_by=>{-desc=>"upd_topic.updated"},
				page=>1,
				rows => $rows
			}
		);
	return \@users;
}

sub find{
        my ($self, $topic_type_id) = @_;
	return $self->schema->resultset('TopicType')->search({'id' => $topic_type_id},{})->first();
}

__PACKAGE__->meta->make_immutable;

1;
